package com.ruoyi.user.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.user.domain.vo.UserLoginVO;
import com.ruoyi.user.utils.MobileMessageUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.user.mapper.TbUserMapper;
import com.ruoyi.user.domain.TbUser;
import com.ruoyi.user.service.ITbUserService;
import org.springframework.util.DigestUtils;

/**
 * 用户Service业务层处理
 * 
 * @author wuxiao
 * @date 2024-08-19
 */
@Service
public class TbUserServiceImpl implements ITbUserService 
{
    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询用户
     * 
     * @param userId 用户主键
     * @return 用户
     */
    @Override
    public TbUser selectTbUserByUserId(Long userId)
    {
        return tbUserMapper.selectTbUserByUserId(userId);
    }

    /**
     * 查询用户列表
     * 
     * @param tbUser 用户
     * @return 用户
     */
    @Override
    public List<TbUser> selectTbUserList(TbUser tbUser)
    {
        return tbUserMapper.selectTbUserList(tbUser);
    }

    /**
     * 新增用户
     * 
     * @param tbUser 用户
     * @return 结果
     */
    @Override
    public int insertTbUser(TbUser tbUser)
    {
        return tbUserMapper.insertTbUser(tbUser);
    }

    /**
     * 修改用户
     * 
     * @param tbUser 用户
     * @return 结果
     */
    @Override
    public int updateTbUser(TbUser tbUser)
    {
        return tbUserMapper.updateTbUser(tbUser);
    }

    /**
     * 批量删除用户
     * 
     * @param userIds 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteTbUserByUserIds(Long[] userIds)
    {
        return tbUserMapper.deleteTbUserByUserIds(userIds);
    }

    /**
     * 删除用户信息
     * 
     * @param userId 用户主键
     * @return 结果
     */
    @Override
    public int deleteTbUserByUserId(Long userId)
    {
        return tbUserMapper.deleteTbUserByUserId(userId);
    }

    @Override
    public AjaxResult loginByPassWord(UserLoginVO userLoginVO) {
        TbUser tbUser = tbUserMapper.selectByAccount(userLoginVO.getAccount());
        if (tbUser == null){
            return AjaxResult.error("账户不存在");
        }
        String bcrypt = DigestUtil.bcrypt(userLoginVO.getPassword());
        System.out.println("加密的密码:" + bcrypt);
        boolean b = DigestUtil.bcryptCheck(userLoginVO.getPassword(), tbUser.getPassword());
        if (!b){
            return AjaxResult.error("密码不对，请重新登录");
        }
        String token = Jwts.builder()
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("account", tbUser.getAccount())
                .compact();
        stringRedisTemplate.opsForValue().set("TOKEN-" + tbUser.getUserId(),token,15, TimeUnit.MINUTES);
        tbUser.setPassword(null);
        tbUser.setToken(token);
        return AjaxResult.success(tbUser);
    }

    @Override
    public AjaxResult getCode(String account) {

        /*发送验证码的方法*/
        //获取随机数
        String code = RandomUtil.randomNumbers(6);

        /*将验证码存入redis*/
        stringRedisTemplate.opsForValue().set("login-code-"+account,code,5,TimeUnit.MINUTES);

        /*发送验证码*/
        MobileMessageUtil.sendMobileMessage(account,code);

        return AjaxResult.success();
    }

    @Override
    public AjaxResult loginByCode(UserLoginVO userLoginVO) {

        /*验证账号密码*/
        String code = stringRedisTemplate.opsForValue().get("login-code-" + userLoginVO.getAccount());

        if (Objects.isNull(code)){
            return AjaxResult.error("请重新发送验证码");
        }

        /*判断验证码是否正确*/
        if (!code.equals(userLoginVO.getCode())){
            return AjaxResult.error("验证码错误");
        }

        /*去数据库查询账号是否存在*/
        TbUser tbUser = tbUserMapper.selectByAccount(userLoginVO.getAccount());

        if (Objects.isNull(tbUser)){
            /*为空 添加到数据库*/
            tbUser.setAccount(userLoginVO.getAccount());
            tbUser.setLoginDate(new Date());
            tbUser.setRegistrationDate(new Date());
            tbUserMapper.insertTbUser(tbUser);
        }

        /*加密获取token*/
        String token = Jwts.builder()
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("account", tbUser.getAccount())
                .compact();
        stringRedisTemplate.opsForValue().set("TOKEN-" + tbUser.getUserId(),token,15, TimeUnit.MINUTES);
        tbUser.setPassword(null);
        tbUser.setToken(token);
        return AjaxResult.success(tbUser);

    }

    @Override
    public AjaxResult register(TbUser tbUser) {

        /*验证账号密码*/
        String code = stringRedisTemplate.opsForValue().get("login-code-" + tbUser.getAccount());

        if (Objects.isNull(code)){
            return AjaxResult.error("请重新发送验证码");
        }

        /*判断验证码是否正确*/
        if (!code.equals(tbUser.getCode())){
            return AjaxResult.error("验证码错误");
        }

        /*去数据库查询账号是否存在*/
        TbUser user = tbUserMapper.selectByAccount(tbUser.getAccount());

        if (Objects.nonNull(user)){
            return AjaxResult.error("账号已存在");
        }

        tbUser.setRoleId(1);

        tbUser.setPassword(DigestUtil.bcrypt(tbUser.getPassword()));

        /*注册*/
        tbUserMapper.insertTbUser(tbUser);

        return AjaxResult.success();
    }
}
